package cc.linker.steplink.crm.merchant.task;

import cc.linker.steplink.crm.commons.lock.RedisLock;
import cc.linker.steplink.crm.merchant.dao.ShopGoodsMapper;
import cc.linker.steplink.crm.merchant.dao.ShopOrderMapper;
import cc.linker.steplink.crm.merchant.service.NewMallService;
import cc.linker.steplink.crm.merchanth5.dao.MallDao;
import cc.linker.steplink.crm.merchanth5.dao.acs.PurchaseProcessDao;
import cc.linker.steplink.crm.merchanth5.service.MallService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 自动确认订单
 *
 * @author wuyue
 */
@Component
public class AutoConfirmOrderTask {

    @Autowired
    private ShopOrderMapper shopOrderMapper;
    @Autowired
    private ShopGoodsMapper shopGoodsMapper;
    @Autowired
    private MallService mallService;
    @Autowired
    private PurchaseProcessDao purchaseProcessDao;
    @Autowired
    private MallDao mallDao;

//    @RedisLock("AutoConfirmOrderTask")
//    @Scheduled(cron = "14 */1 * * * ?")
    public void autoConfirmOrderTask() {
        // 获取待确认订单sn,orderSn,customerId,orgId
        List<Map<String, Object>> orderInfo = shopOrderMapper.getOrderSnWhereAutoConfirm();
        for (Map<String, Object> map : orderInfo) {
            map.put("objectId", map.get("orderSn"));
            mallService.addToDealData(map, 5);
        }
        // 自动确认
        shopOrderMapper.updateStatusWhereAutoConfirm();
        // 自动关闭超过一小时未付款的订单
        List<String> orderIds = shopOrderMapper.listOrderWhereExpired();
        if (orderIds.isEmpty()) {
            return;
        }
        shopOrderMapper.closeOrderWhereExpired(orderIds);
        // 订单关闭后恢复库存
        List<Map<String, Object>> orders = shopOrderMapper.listOrderByOrderId(orderIds);
        for (Map<String, Object> order : orders) {
            Long goodsId = Long.valueOf(order.get("goodsId").toString());
            Long mallsGoodsId =  purchaseProcessDao.getMallsGoodsIdByGoodsId(goodsId);
            String skuId = "";
            if (order.get("skuId") != null && !"".equals(order.get("skuId"))) {
                skuId = order.get("skuId").toString();
            }
            Integer goodsNum = 0;
            if (order.get("goodsNum") != null && !"".equals(order.get("goodsNum"))) {
                goodsNum = Integer.valueOf(order.get("goodsNum").toString());
            }
//            // 有sku
            shopGoodsMapper.updateSkuCount(order);
            shopGoodsMapper.updateGoodsCount(order);
        }
    }
}
